//
//  ZHYCacheManager.m
//  ZHYProject
//
//  Created by lc4y on 2017/12/21.
//  Copyright © 2017年 dtl. All rights reserved.
//

#import "ZHYCacheManager.h"

#define CachePath [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/ZHYCacheDict.plist"]

@interface ZHYCacheManager ()

@property (nonatomic,strong) NSMutableDictionary *cacheDict;

@end

@implementation ZHYCacheManager

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.cacheDict = [NSMutableDictionary dictionary];
        [self.cacheDict setValuesForKeysWithDictionary:[NSMutableDictionary dictionaryWithContentsOfFile:CachePath]];
    }
    
    return self;
}
+ (ZHYCacheManager *)cacheMananger {
    
    static ZHYCacheManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    
    return manager;
}

- (void)saveData:(id)value forKey:(id)key {
    // 保存缓存
    [self.cacheDict setObject:value forKey:key];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        BOOL isSaveSuccess = [self.cacheDict writeToFile:CachePath atomically:YES];
        
        if(!isSaveSuccess) {
            NSLog(@"保存数据失败");
        }
    });
}

- (id)fetchDataForKey:(id)key {
    // 从缓存中读取
    return [self.cacheDict valueForKey:key];
}

- (void)removeDataForKey:(id)key {
    [self.cacheDict removeObjectForKey:key];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        BOOL isSaveSuccess = [self.cacheDict writeToFile:CachePath atomically:YES];
        
        if(!isSaveSuccess) {
            NSLog(@"删除数据失败");
        }
    });
}

- (BOOL)clearAllData {
    self.cacheDict = [NSMutableDictionary dictionary];
    return [[NSFileManager defaultManager] removeItemAtPath:CachePath error:nil];
}

@end
